﻿using System;
using System.Linq;
using Csla;
using Csla.Data;
using BizControl.DalLinq;
using BizControl.Library.Security;
using BizControl.Library.BusinessObjects.Models;
using BizControl.Library.BusinessObjects.People;
using BizControl.Library.Criterias;
using BizControl.Resources;
using System.Security;
using System.Collections.Generic;

namespace BizControl.Library.BusinessObjects.Activities
{
  [Serializable()]
  public class IndependentActivityList : ReadOnlyListBase<IndependentActivityList, ActivityInfo>
  {
    internal void AllowChange()
    {
      IsReadOnly = false;
    }

    internal void ForbidChange()
    {
      IsReadOnly = true;
    }

    #region  Factory Methods

    public static IndependentActivityList NewIndependentActivityList()
    {
      return DataPortal.Create<IndependentActivityList>();
    }

    public static IndependentActivityList GetIndependentActivityList()
    {
      var person = ((BizControlPrincipal)ApplicationContext.User).Person;
      var model = ((BizControlPrincipal)ApplicationContext.User).Model;
      return DataPortal.Fetch<IndependentActivityList>(new PersonAndModelCriteria(person, model));
    }

    #endregion

    #region  Data Access

    private void DataPortal_Create()
    {
    }

    private void DataPortal_Fetch(PersonAndModelCriteria criteria)
    {
      RaiseListChangedEvents = false;
      IsReadOnly = false;
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        var activities = ActivityList.GetActivityList();
        foreach (var activity in activities)
        {
          var dependent = from l in ctx.DataContext.ActivityLinks
                          where l.Activity2 == activity.Id
                          select l;
          if (dependent.Count() == 0)
            Add(new ActivityInfo(activity));
        }
      }
      IsReadOnly = true;
      RaiseListChangedEvents = true;
    }

    #endregion

  }
}
